﻿using System.Collections.Generic;
using UFIDA.U9.WSS.ProxyService.AccessProxy.Configuration;
using UFSoft.UBF.Util.Context;
using UFSoft.UBF.Util.Log;

namespace UFIDA.U9.WSS.ProxyService.AccessProxy
{
    /// <summary>
    ///     授权代理管理类
    /// </summary>
    public sealed class AccessProxyManager
    {
        private static AccessProxyManager _instance;
        private static readonly object Lock = new object();
        private static readonly object InitLock = new object();
        private static readonly ILogger Logger = LoggerManager.GetLogger(typeof(AccessProxyManager));
        private Dictionary<string, List<string>> _accessProxyDict;
        private bool _isInited;

        private AccessProxyManager()
        {
        }

        public static AccessProxyManager Instance
        {
            get
            {
                if (_instance != null)
                {
                    if (!_instance._isInited)
                    {
                        _instance.Init();
                    }

                    return _instance;
                }

                lock (Lock)
                {
                    if (_instance == null)
                    {
                        _instance = new AccessProxyManager();
                        _instance.Init();
                    }
                    else if (!_instance._isInited)
                    {
                        _instance.Init();
                    }

                    return _instance;
                }
            }
        }

        /// <summary>
        ///     是否允许访问
        /// </summary>
        /// <param name="proxyType"></param>
        /// <returns></returns>
        public bool IsAccess(string proxyType)
        {
            if (PlatformContext.Current == null || string.IsNullOrEmpty(PlatformContext.Current.UserCode)) return false;
            if (string.IsNullOrEmpty(proxyType)) return false;
            string proxyTypeLower = proxyType.ToLower().Replace(" ", string.Empty);
            if (string.IsNullOrEmpty(proxyTypeLower)) return false;
            if (!_accessProxyDict.ContainsKey(proxyTypeLower))
            {
                if (proxyTypeLower.Length > 4 && proxyTypeLower.EndsWith(".dll"))
                {
                    proxyTypeLower = proxyTypeLower.Substring(0, proxyTypeLower.Length - 4);
                    if (!_accessProxyDict.ContainsKey(proxyTypeLower)) return false;
                }
                else if (!proxyTypeLower.EndsWith(".dll"))
                {
                    proxyTypeLower += ".dll";
                    if (!_accessProxyDict.ContainsKey(proxyTypeLower)) return false;
                }
                else
                {
                    return false;
                }
            }

            string userCodeLower = PlatformContext.Current.UserCode.ToLower();
            List<string> userCodeList = _accessProxyDict[proxyTypeLower];
            return userCodeList.Contains(userCodeLower);
        }

        /// <summary>
        ///     初始化
        /// </summary>
        public void Init()
        {
            lock (InitLock)
            {
                if (_isInited) return;
                if (_accessProxyDict != null) return;
                Logger.Debug("AccessProxyManager init...");
                _accessProxyDict = new Dictionary<string, List<string>>();
                AccessProxysSectionGroup accessProxySectionGroup = AccessProxysSectionGroup.GetConfig();
                if (accessProxySectionGroup == null) return;
                foreach (GroupSection groupSection in accessProxySectionGroup.Groups)
                {
                    if (groupSection.Proxys == null || groupSection.Proxys.Count == 0) continue;
                    string userCodes = groupSection.User;
                    if (string.IsNullOrWhiteSpace(userCodes)) continue;
                    string[] arrUserCode = userCodes.Split(',');
                    foreach (ProxySection ProxySection in groupSection.Proxys)
                    {
                        if (string.IsNullOrWhiteSpace(ProxySection.ProxyType)) continue;
                        string proxyTypeLower = ProxySection.ProxyType.ToLower().Replace(" ", string.Empty);
                        if (string.IsNullOrWhiteSpace(proxyTypeLower)) continue;
                        List<string> accessUserList;
                        if (!_accessProxyDict.ContainsKey(proxyTypeLower))
                        {
                            accessUserList = new List<string>();
                            _accessProxyDict.Add(proxyTypeLower, accessUserList);
                        }
                        else
                        {
                            accessUserList = _accessProxyDict[proxyTypeLower];
                        }

                        foreach (string userCode in arrUserCode)
                        {
                            if (string.IsNullOrEmpty(userCode)) continue;
                            string userCodeLower = userCode.ToLower();
                            if (accessUserList.Contains(userCodeLower)) continue;
                            accessUserList.Add(userCodeLower);
                        }
                    }
                }

                _isInited = true;
            }
        }
    }
}